package com.juzhencms.apps.busi.web;



import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.juzhencms.apps.base.busi.service.WeixinApiService;
import com.juzhencms.apps.base.common.annotation.UserLoginToken;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.SpringContextUtil;
import com.juzhencms.apps.base.common.util.StringUtil;
import com.juzhencms.apps.base.common.util.WebUtil;
import com.juzhencms.apps.busi.entity.AdminLoginUser;
import com.juzhencms.apps.busi.service.UserService;
import com.juzhencms.apps.base.common.util.HttpUtil;
//import com.juzhencms.apps.common.util.SHA1;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

@RestController
@Slf4j
@RequestMapping("/adminWeixin")
public class AdminWeixinController extends BaseController{
	
	@Autowired
	private UserService userService;
	@Autowired
	private WeixinApiService weixinApiService;
	@RequestMapping(value="/getBaseCode",method = RequestMethod.GET,produces="text/html;charset=UTF-8")
	@ResponseBody
    public String getBaseCode(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		String action=request.getParameter("action");
		log.info("getBaseCode action:"+action);
		
		/*//如果当前用户已经登录了，之前跳转即可
		AdminLoginUser loginUser=this.getLoginUser();
		if(loginUser!=null) {
			
		}*/
		
		
		//判断是否是微信浏览器
		String userAgent = this.getRequest().getHeader( "user-agent" ).toLowerCase();
	
		//如果当前未登录并且在微信中并且则跳转获取code，从而获取openid
		if (userAgent.indexOf( "micromessenger" )>- 1){ 
			
			
			//配置回调的地址及参数
			String callbackUrl=Config.getValue("app.adminapiDomain")+action;
			String jumpUrl="https://open.weixin.qq.com/connect/oauth2/authorize?"
					+ "appid="+Config.getValue("weixin.appId")
					+ "&redirect_uri="+java.net.URLEncoder.encode(callbackUrl,"UTF-8")
					+ "&response_type=code&scope=snsapi_base"
					//+ "&state="+StringUtil.urlEncode(action)//这个参数不能超过128字符
					+ "#wechat_redirect";
			
			log.info("getBaseCode sendRedirect:"+jumpUrl);
			this.getResponse().sendRedirect(jumpUrl);
			
		}else {
			Map data=new HashMap();
			
			data.put("result", 0);
			data.put("name", "操作失败");
			data.put("desc", "请使用微信重新扫码");
			return this.templateResult("mobileResult", data);
		}
		
		return null;
    }
	
	
	
	
	//绑定微信账号
	@RequestMapping(value="/bindWeixin/{userId}",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String  bindWeixin(@PathVariable("userId") String userId,HttpServletRequest request,HttpServletResponse response){
		Map data=new HashMap();
		data.put("title", "微信账号绑定");
		
		Map user=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.user+" where id=? and del_flag=0 ", new Object[] {userId});
		if(user==null) {

			data.put("result", 0);
			data.put("name", "绑定失败");
			data.put("desc", "用户不存在");
			return this.templateResult("mobileResult", data);
		}
		
		if(user.get("weixin_openid")!=null && !user.get("weixin_openid").equals("")) {

			data.put("result", 0);
			data.put("name", "绑定失败");
			data.put("desc", "当前用户已经绑定了微信号，请先解除绑定后再操作");
			return this.templateResult("mobileResult", data);
		}
		
		
		//从参数中获取code
		String code=this.getRequest().getParameter("code");
		String appid=Config.getValue("weixin.appId");
		String secret=Config.getValue("weixin.appSecret");
		//获取用户openid
		String urlSuffix="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
		String resp = HttpUtil.sendGetUrl(urlSuffix);
		log.info("oauth2 result:"+resp);
		// 不改变参数的顺序
		Map respMap = JSON.parseObject(resp, LinkedHashMap.class,Feature.OrderedField);
		if(StringUtil.isNotNullOrEmpty(respMap.get("openid"))) {
			
			String openid=respMap.get("openid").toString();
			

			
			//判断此openid是否绑定了其他用户
			Map olduser=this.getCommonService().getJdbcDao().queryRow("select id,user,name from "+DBTable.user+" where del_flag=0 and weixin_appid=? and weixin_openid=? and id!=? limit 0,1", new Object[] {appid,openid,userId});
			if(olduser!=null) {

				data.put("result", 0);
				data.put("name", "绑定失败");
				data.put("desc", "当前微信账号已经绑定了用户"+olduser.get("olduser")+"("+olduser.get("name")+"),请先解除此用户绑定的微信账号,然后再进行绑定操作");
				return this.templateResult("mobileResult", data);
			}else {
				
				//获取accessToken
				String accessToken=weixinApiService.getAccessToken(appid, secret);
				
				
				//调用接口判断用户是否关注了微信公众号
				
				
				String subscribeApiUrl="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
				log.info("info url:"+subscribeApiUrl);
				String subscribeString = HttpUtil.sendGetUrl(subscribeApiUrl);
				log.info("info result:"+subscribeString);
				
				if(subscribeString!=null && !subscribeString.equals("")) {
					Map subscribeData=JSON.parseObject(subscribeString,Map.class);
					if(subscribeData==null || subscribeData.get("subscribe")==null || subscribeData.get("subscribe").toString().equals("0") ) {

						data.put("result", 0);
						data.put("name", "绑定失败");
						data.put("desc", "请先关注微信公众号:"+Config.getValue("weixin.account"));
						return this.templateResult("mobileResult", data);
					}else {
						//执行绑定
						this.getCommonService().getJdbcDao().updateSql("update "+DBTable.user+" set weixin_appid=?,weixin_openid=? where id=?", new Object[] {appid,openid,userId});
						
						
						data.put("result", 1);
						data.put("name", "绑定成功");
						data.put("desc", "微信账号绑定成功");
						return this.templateResult("mobileResult", data);
					}
				}
			}
		}
		
		
		data.put("result", 0);
		data.put("name", "操作失败");
		data.put("desc", "微信账号获取失败");
		return this.templateResult("mobileResult", data);
		
		
		
	}
	
	//解除绑定微信账号
	@RequestMapping(value="/unbindWeixin",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String  unbindWeixin(HttpServletRequest request,HttpServletResponse response){
		
		AdminLoginUser loginUser = this.getLoginUser();
		int id = loginUser.getId();
		if(request.getParameter("id")!=null && !request.getParameter("id").equals("")) {
			id=Integer.parseInt(request.getParameter("id"));
		}
		this.getCommonService().getJdbcDao().updateSql("update "+DBTable.user+" set weixin_appid='',weixin_openid='' where id=? ",new Object[] {id});
		
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	
	//绑定微信账号
	@RequestMapping(value="/login",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String  weixinLogin(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		String action=request.getParameter("action");
		log.info("weixinLogin action:"+action);
		
		
		
		//从参数中获取code
		String code=this.getRequest().getParameter("code");
		String appid=Config.getValue("weixin.appId");
		String secret=Config.getValue("weixin.appSecret");
		//获取用户openid
		String urlSuffix="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
		String resp = HttpUtil.sendGetUrl(urlSuffix);
		//log.info("oauth2 result:"+resp);
		// 不改变参数的顺序
		Map respMap = JSON.parseObject(resp, LinkedHashMap.class,Feature.OrderedField);
		if(StringUtil.isNotNullOrEmpty(respMap.get("openid"))) {
			
			String openid=respMap.get("openid").toString();
			
			//查找匹配的用户
			Map user=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.user+" where del_flag=0 and publish=1 and weixin_appid=? and weixin_openid=? limit 0,1", new Object[] {appid,openid});

			log.info("weixinLogin user:"+JSON.toJSONString(user));
			
			if(user!=null) {
				//设置自动登录
				//生成jwt签名
				String userToken=userService.createUserToken(user);
				//将用户信息存储到cookie
				this.getUserService().setLoginCookie(userToken, "1", request, response);
				
				//执行跳转操作
				String jumpUrl=null;
				if(action.indexOf("#")>=0) {
					jumpUrl=Config.getValue("app.adminwebDomain")+action;
				}else {
					jumpUrl=Config.getValue("app.adminapiDomain")+action;
				}
						
				
				log.info("weixinLogin sendRedirect:"+jumpUrl);
				this.getResponse().sendRedirect(jumpUrl);
				return null;
			}
		}
		
		Map data=new HashMap();
		
		data.put("result", 0);
		data.put("name", "身份验证失败");
		data.put("desc", "请登录系统绑定微信号后再进行操作");
		return this.templateResult("mobileResult", data);
		
		
		
	}
	
	
	
	
}
